
#include <qt/tradingengine.hpp>

namespace QuantLib {

	std::vector<Performance> TradingEngine::performBacktest(std::vector<Date> startDates, BigInteger backtestingLengthDays) {

		// First, check that the inputs are compatible with the data the class has:
		//	All start dates need to be in the available dates
		//	The last start date cannot run off the end

		// Now run over the dates and store the performance at each date
		std::vector<Performance> backtestResults = std::vector<Performance>();
		std::vector<Date> eventDates = _initialPortfolio.getEventDates();

		for (int i = 0; i < startDates.size(); ++i) {
			Date startDate = startDates[i];
			Portfolio p(_initialPortfolio);
			Performance perf(startDate);
			p.initialisePortfolio(startDate, _initialPortfolio.getAvailableCash());
			
			int j = std::find(eventDates.begin(),eventDates.end(),startDate) - eventDates.begin();
			Date endDate = startDate + backtestingLengthDays;
			while (eventDates[j] < endDate) {
				p.moveDateForward(eventDates[j]);
				std::vector<TradeOrder> orders = _strategy->getAction(p);
				if (orders.size() > 0) {
					for (int k=0; k < orders.size(); ++k)
						p.placeOrder(orders[k]);
				}
				perf.setObservation(eventDates[j], p.getCurrentValue());
				j++;
			}
			backtestResults.push_back(perf);
		}
		return backtestResults;
	}
}